<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天</title>
</head>
<body>
    <h2>FastAPI 聊天室</h2>
    <input id="username" placeholder="用户名" />
    <button onclick="connect()">连接</button>

    <div>
        <input id="to" placeholder="发给谁 (留空为了群发)" />
        <input id="message" placeholder="消息内容" />
        <button onclick="send()">发送</button>
    </div>

    <ul id="messages"></ul>>

    <script>
        let ws = null;
        function connect() {
            const username = document.getElementById("username").value;
            ws = new WebSocket("ws://localhost:8000/ws/chat/?username=" + username);
            ws.onmessage = event => {
                const li = document.createElement("li")
                li.innerText = event.data;
                document.getElementById("message").appendChild(li)
            };
        }

        function send() {
            const msg = document.getElementById("message").value;
            const to = document.getElementById("to").value;
            const type = to ? "private" : "broadcast";
            ws.send(JSON.stringify({type, message:msg, to}))
        }
    </script>
</body>
</html>